Page({
  data: {
    //商品详情
    productmess: null,
    //是否
    pushstatus: false,
    //商品id
    productid: "",
    //查看资质窗口
    popupshow: false,
    //位置信息
    location: {
      //经度
      longitude: null,
      // 纬度
      latitude: null,
    },
    //是否请求中
    loading: true,
  },
  onLoad: function (options) {
    let that = this;
    tt.showLoading({
      title: "加载中...",
    });
    //获取经纬度信息
    tt.getLocation({
      success(res: any) {
        that.setData({
          location: res,
        });
        //查询订单详情
        that.getqueryproduct(options.productid, true);
      },
      fail(res) {
        console.log("获取位置失败", res);
        //查询订单详情
        that.getqueryproduct(options.productid, false);
      },
    });
  },
  //获取订单详情
  getqueryproduct(productid: any, ifgetloaction: boolean) {
    let that = this;
    new Promise((resolve: any, reject: any) => {
      tt.request({
        url: getApp().globalData.baseurl + "/douyin/query_product",
        data: {
          product_id: productid,
        },
        header: {
          "content-type": "application/json",
        },
        method: "POST",
        responseType: "text",
        success(res: any) {
          if (res.data.code === 0) {
            resolve(res.data.data);
          } else {
            reject("请求报错");
          }
        },
        fail(err: any) {
          reject(err.errMsg);
        },
      });
    })
      .then((res: any) => {
        //商品服务类型
        let refund_string = "";
        if (res.sku.attr_key_value_map.refund_type) {
          JSON.parse(res.sku.attr_key_value_map.refund_type).forEach(
            (item: any, index: any) => {
              if (index !== 0) {
                refund_string = refund_string + "·" + item;
              } else {
                refund_string = item;
              }
            }
          );
        }
        //如果获取到了位置信息判断距离(单位公里)
        let shops: any = [];
        if (ifgetloaction) {
          //判断距离
          res.shops.forEach((item: any) => {
            shops.push({
              data: item,
              distance: that.getDistance(
                that.data.location.latitude,
                that.data.location.longitude,
                item.latitude,
                item.longitude
              ),
            });
          });
        } else {
          res.shops.forEach((item: any) => {
            shops.push({
              data: item,
              distance: null,
            });
          });
        }
        let productmess: any = {
          //商品主体
          productitem: res,
          //折扣
          discount: (
            (res.sku.actual_amount / res.sku.origin_amount) *
            10
          ).toFixed(2),
          //图片列表
          imglist: JSON.parse(res.product.attr_key_value_map.image_list),
          //商品服务类型
          refund_string: refund_string,
          //团购详情
          commodity: JSON.parse(res.sku.attr_key_value_map.commodity),
          //使用日期限制
          use_date: JSON.parse(res.product.attr_key_value_map.use_date),
          //使用时间限制
          use_time: JSON.parse(res.product.attr_key_value_map.use_time),
          //预约规则
          appointment: JSON.parse(res.product.attr_key_value_map.appointment),
          //使用规则
          description_rich_text: JSON.parse(
            res.product.attr_key_value_map.description_rich_text
          ),
          shops: shops,
        };
        that.setData({
          loading: false,
          productmess: productmess,
          productid: productid,
        });
        tt.hideLoading({});
      })
      .catch((err: any) => {
        tt.showToast({
          title: err,
          icon: "fail",
          duration: 2000,
        });
      });
  },
  getDistance(lat1: number, lng1: number, lat2: number, lng2: number) {
    var radLat1 = (lat1 * Math.PI) / 180.0;
    var radLat2 = (lat2 * Math.PI) / 180.0;
    var a = radLat1 - radLat2;
    var b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
    var s =
      2 *
      Math.asin(
        Math.sqrt(
          Math.pow(Math.sin(a / 2), 2) +
            Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
        )
      );
    s = s * 6378.137; // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000;
    return s.toFixed(2);
  },
  //改变展开收起状态
  changePushstatus() {
    let that = this;
    if (that.data.pushstatus) {
      that.setData({
        pushstatus: false,
      });
    } else {
      that.setData({
        pushstatus: true,
      });
    }
  },
  //提交订单
  goStorelist() {
    tt.setStorageSync("shops", this.data.productmess.shops);
    tt.navigateTo({
      url: "/pages/storelist/storelist",
    });
  },
  //我的订单
  goMyorder() {
    tt.navigateTo({
      url: "/pages/myorder/myorder",
    });
  },
  //拨打电话
  callPhone(event: any) {
    if (event.currentTarget.dataset.phone) {
      tt.makePhoneCall({
        phoneNumber: event.currentTarget.dataset.phone,
      });
    }
  },
  //获取商品信息
  getGoodsInfo(event: any) {
    return new Promise((resolve) => {
      // 在此处开发者可以进行商品数据请求，获取商品信息
      // 然后将商品信息传入 resolve 函数
      resolve({
        minLimits: 1,
        maxLimits: 999,
        dateRule: "周一至周日可用",
        validation: {
          phoneNumber: {
            required: true, // 手机号是否必填
          },
        },
      });
    });
  },
  //发起订单前的准备工作
  userLogin(event: any) {
    return new Promise((resolve: any, reject: any) => {
      if (getApp().globalData.userinfo) {
        resolve();
      } else {
        tt.login({
          success() {
            resolve();
          },
          fail() {
            reject();
          },
        });
      }
    });
  },
  //支付结果回调
  handlePay(event: any) {
    const { status, outOrderNo, result } = event.detail;
    if (status === "success") {
      const { code } = result;
      if (code === 0) {
        //调起支付成功
        tt.navigateBack({
          delta: 1,
        });
        console.log("调起支付成功");
      }
    } else {
      // 调起支付失败
      tt.showToast({
        title: "支付失败",
        icon: "fail",
        duration: 1000,
      });
      console.log("调起支付失败" + event.detail.status);
    }
  },
  //查看资质
  checkQualif() {
    let that = this;
    that.setData({
      popupshow: true,
    });
  },
  //关闭弹出层
  closePopup() {
    let that = this;
    that.setData({
      popupshow: false,
    });
  },
  //打开导航
  openLocation(event: any) {
    let data = event.currentTarget.dataset;
    tt.openLocation({
      latitude: data.latitude,
      longitude: data.longitude,
      name: data.name,
      address: data.address,
      scale: 18,
      success() {
        console.log("打开地图成功");
      },
      fail(err) {
        console.log("打开地图失败:", err.errMsg);
      },
    });
  },
  //返回首页
  goHome() {
    tt.navigateTo({
      url: "/pages/index/index",
    });
  },
});
